const {createSlice, configureStore} = require('@reduxjs/toolkit')

// const DEFAULT_DATA = {
//   nodeById: {
//     nodes: {
//       'simple-page': {
//         type: 'simple-page',
//         data: {},
//       },
//       'name-card': {
//         type: 'name-card',
//         data: {},
//       }
//     },
//     allIds: ['simple-page', 'name-card'],
//   }
// }
// const addNode = (state, action) => {
//   const { payload } = action
//   return {
//     ...state,
//     [payload.id]: {
//       ...payload,
//     }
//   }
// }

// const nodesById = (state, action) => {
//   switch(action.type) {
//     case 'ADD':
//       return addNode(state, action)
//   }
// }
// const addNodeId = (state = [], action) => {
//   return state.concat(action.payload.id)
// }

// const allNodes = (state = [], action) => {
//   switch (action.type) {
//     case 'ADD':
//       return addNodeId(state, action)
//   }
// }

const nodesByIdSlice = createSlice({
  name: 'nodesById',
  initialState: {},
  reducers: {
    addNode: (state = {}, action) => {
      const { payload: { parentId, ...node } } = action
      if (node.type === 'Page') {
        // 保证根组件唯一
        node.id = 'root'
      }
      // 节点
      state[node.id] = node
      // 挂载
      if (parentId) {
        const children = state[parentId].children || []
        state[parentId].children = children.concat(node.id)
      }
    }
  }
})

// const allNodeSlice = createSlice({
//   name: 'allNodes',
//   initialState: [],
//   reducers: {
//     addNodeId: (state = [], action) => {
//       state.push(action.payload.id)
//     }
//   }
// })

const { addNode } = nodesByIdSlice.actions
// const { addNodeId } = allNodeSlice.actions

const store = configureStore({
  reducer: {
    nodesById: nodesByIdSlice.reducer,
    // allNode: allNodeSlice.reducer,
  }
})

store.subscribe(() => {
  console.log('listening', store.getState())
  console.log('---------------------------------')
})

// 添加组件 simple-page
store.dispatch(addNode({
  id: 'root',
  name: 'simple-page',
  type: 'Page'
}))
// store.dispatch(addNodeId({
//   id: 'root',
//   name: 'simple-page',
//   type: 'Page'
// }))

// 添加组件 name-card
store.dispatch(addNode({
  id: 'name-card',
  name: 'name-card',
  type: 'Leaf',
  parentId: 'root'
}))
// store.dispatch(addNodeId({
//   id: 'name-card',
//   name: 'name-card',
//   type: 'Leaf',
//   parentId: 'root'
// }))
// 添加组件 work-project
store.dispatch(addNode({
  id: 'work-project',
  name: 'work-project',
  type: 'Leaf',
  parentId: 'root'
}))
// store.dispatch(addNodeId({
//   id: 'work-project',
//   name: 'work-project',
//   type: 'Leaf',
//   parentId: 'root'
// }))
function visitor(id) {
  const { nodesById: nodes } = store.getState()
  const node = nodes[id]
  // 访问
  console.log('visited: ', node)
  const children = node.children ? node.children.concat() : [];
  // 下探
  while(children.length) {
    visitor(children.shift())
  }
}

visitor('root')
